// 邮件订阅
import React, { useState, useEffect }  from 'react';
import { Form, Input, InputNumber, message, Modal, Select, Radio, TreeSelect, Switch } from 'antd';

import { subscribeGet, subscribeSave, selectOrgPosWithEmpTree } from 'src/services/AnalyseManage';

const { SHOW_CHILD } = TreeSelect;

interface Iprops {
	modalVisible:boolean
	pageId:any
	closeModal:any
	onSuccess:any
}

const weekOptions = [
	{ label: '星期一', value: 1 },
	{ label: '星期二', value: 2 },
	{ label: '星期三', value: 3 },
	{ label: '星期四', value: 4 },
	{ label: '星期五', value: 5 },
	{ label: '星期六', value: 6 },
	{ label: '星期日', value: 7 }
];

/* const treeData = [
	{
		title: 'Node1',
		value: '0-0',
		key: '0-0',
		children: [
			{
				title: 'Child Node1',
				value: '0-0-0',
				key: '0-0-0',
			},
		],
	},
	{
		title: 'Node2',
		value: '0-1',
		key: '0-1',
		children: [
			{
				title: 'Child Node3',
				value: '0-1-0',
				key: '0-1-0',
			},
			{
				title: 'Child Node4',
				value: '0-1-1',
				key: '0-1-1',
			},
			{
				title: 'Child Node5',
				value: '0-1-2',
				key: '0-1-2',
			},
		],
	},
]; */

// eslint-disable-next-line react/display-name
const EmailSub = React.forwardRef ( ( props: Iprops, formRef: any ) => {
	const [ selectedNodes, setSelectedNodes ] = useState( [] );
	const [ treeData, setTreeData ] = useState( [] );
	const [ jobType, setJobType ] = useState( null );
	const [ receiverRequired, setReceiverRequired ] = useState( false );	//	收件人是否必填，开启则必填，关闭则不必填
	
	const [ form ] = Form.useForm();

	const handleCancle = () => {
		props.closeModal( false );
		// form.resetFields();
	};
	
	const handleOk = () => {
		form.validateFields().then( value => {
			handleSave( value );
			handleCancle();
		} ).catch( info => {
			message.warning( '请完善信息' );
		} );
	};

	// 订阅配置保存
	const handleSave = async ( data ) => {
		console.log( '-- ok ---', data );
		const { jobType, dayOfMonths, dayOfWeeks, hour, minute } = data;
		const cronData = { jobType, dayOfMonths: dayOfMonths ? [ dayOfMonths ] : null, dayOfWeeks, hour, minute, second: 0 };
		/* const receiver = selectedNodes.map( node => {
			return {
				email: node.email,
				userId: node.id,
				userName: node.name,
			};
		} ); */
		let param = {
			pageId: props.pageId,
			mailSubject: data.mailSubject,
			receiver: selectedNodes,
			status: data.status ? '1' : '0',
			cronData: JSON.stringify( cronData ),
		};
		const res = await subscribeSave( param );
		if ( res.data.success ) {
			props.onSuccess( data );
			message.success( '保存成功' );
		}
	};

	const jobTypeChange = ( e ) => {
		setJobType( e.target.value );
	};

	// 查询订阅配置
	const getData = async () => {
		const res = await subscribeGet( props.pageId );
		if ( res.data.success ) {
			let data = res.data.data;
			if ( !data ) return;
			let cronData = JSON.parse( data.cronData );
			setSelectedNodes( JSON.parse( JSON.stringify( data.receiver ) ) );
			data.status = data.status === '1' ? true : false;
			setReceiverRequired( data.status );
			data.receiver = data.receiver.map( o => o.userId );
			console.log( '-- data ---', data );

			if ( cronData ) {
				if ( cronData.dayOfMonths && cronData.dayOfMonths.length ) {
					cronData.dayOfMonths = cronData.dayOfMonths[ 0 ];
				}
				console.log( '-- cronData ---', cronData.jobType );
				setJobType( cronData.jobType );
			}

			setTimeout( () => {
				form.setFieldsValue( { ...data, ...cronData } );
			}, 100 );
			
		}
	};

	// 递归树结构
	const getChildren = ( node ) => {
		if ( node.children && node.children.length ) {
			return node.children.map( item => {
				return {
					...item,
					title: item.name,
					key: item.id,
					value: item.id,
					children: getChildren( item ),
					disableCheckbox: item.type !== 'USER' && !( item.children && item.children.length ),
				};
			} );
		} else {
			return null;
		}
	};

	// 获取人员数据
	const getTreeData = async () => {
		const res = await selectOrgPosWithEmpTree( { type: 'ORGANIZATION' } );
		if ( res.data.success ) {
			const data = res.data.data;
			const treeData = data.map( node => {
				return {
					title: node.name,
					key: node.id,
					value: node.id,
					children: getChildren( node ),
				};
			} );
			setTreeData( treeData );
		}
	};

	const getUserNode = ( node ) => {
		let data = [];
		if ( node.type === 'USER' ) {
			data.push( node );
		} else if ( node.children.length ) {
			data = node.children.map( item => {
				return getUserNode( item.props );
			} );
			data = [].concat.apply( [], data );
		}
		return data;
	};

	// 选择人员
	const changeNode = ( value, label, extra ) => {
		console.log( '-- changeNode ---', value, label, extra );
		if ( value.length ) {
			let nodes = extra.allCheckedNodes.map( item => {
				let node = item.node ? item.node.props : item.props;
				return getUserNode( node );
			} );
			nodes = [].concat.apply( [], nodes );
			console.log( '==== SelectedNodes ====', nodes );
			let selectedNodes = nodes.map( node => {
				return {
					email: node.email,
					userId: node.id,
					userName: node.name,
				};
			} );
			setSelectedNodes( selectedNodes );
		} else {
			setSelectedNodes( [] );
		}
	};

	const handleSwitchChange = ( value ) => {
		setReceiverRequired( value );
	};

	useEffect( () => {
		if ( !props.modalVisible ) return;
		if ( props.pageId ) {
			getData();
		}
		if ( !treeData.length ) {
			getTreeData();
		}
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ props.modalVisible, props.pageId, treeData ] );

	// 定时设置配置
	const taskConfig = [
		{
			name: 'jobType',
			label: '定时配置',
			hide: false,
			rules: [ { required: true, message: '请选择定时配置' } ],
			component: <Radio.Group onChange={ jobTypeChange }>
				{/* <Radio.Button value={0}>每分钟</Radio.Button> */}
				<Radio.Button value={4}>每小时</Radio.Button>
				<Radio.Button value={1}>每天</Radio.Button>
				<Radio.Button value={3}>每周</Radio.Button>
				<Radio.Button value={2}>每月</Radio.Button>
			</Radio.Group>
		},
		{
			name: 'dayOfMonths',
			label: '日期',
			hide: jobType !== 2,
			initialValue: 1,
			rules: [ { required: true, message: '请输入日期' } ],
			component: <InputNumber min={1} max={31} />
		},
		{
			name: 'dayOfWeeks',
			label: '星期几',
			hide: jobType !== 3,
			initialValue: [ 1 ],
			rules: [ { required: true, message: '请选择星期几' } ],
			component: <Select mode="multiple" allowClear>
				{
					weekOptions.map( item => {
						return (
							<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
						);
					} )
				}
			</Select>
		},
		{
			name: 'hour',
			label: '小时点',
			hide: [ 0, 4, null ].includes( jobType ),
			initialValue: 1,
			rules: [ { required: true, message: '请输入小时点' } ],
			component: <InputNumber min={0} max={23} />
		},
		{
			name: 'minute',
			label: '分钟点',
			hide: jobType < 1,
			initialValue: 0,
			rules: [ { required: true, message: '请输入分钟点' } ],
			component: <InputNumber min={0} max={59} />
		},
		/* {
			name: 'second',
			label: '秒数',
			hide: jobType === null,
			initialValue: 0,
			rules: [ { required: true, message: '请输入秒数' } ],
			component: <InputNumber min={0} max={59} />
		}, */
	];

	return (
		<Modal visible={props.modalVisible}
			okText={'确定'}
			cancelText={'取消'}
			onCancel={handleCancle}
			onOk={handleOk}
			title={'邮件订阅'}>
			<Form form={form} ref={ formRef } labelCol={{ span: 6 }}>
				<Form.Item label="邮件标题" name="mailSubject"
					rules={[ { required: true, message: '邮件标题不能为空' } ]}>
					<Input autoComplete="off" />
				</Form.Item>
				{/* 定时配置 */}
				{
					taskConfig.map( ( v, i ) => {
						return v.hide ? null : (
							<Form.Item label={ v.label } name={ v.name } initialValue={ v.initialValue } rules={ v.rules } key={ `job${i}` }>
								{ v.component }
							</Form.Item>
						);
					} )
				}

				<Form.Item label="收件人选择" name="receiver"
					rules={[ { required: receiverRequired, message: '收件人不能为空' } ]}>
					<TreeSelect style={ { width: '100%' } }
						allowClear
						treeDefaultExpandAll
						treeNodeFilterProp="title"
						treeData={ treeData }
						treeCheckable={ true }
						onChange={ changeNode }
						showCheckedStrategy={ SHOW_CHILD }
						placeholder={ '请选择' } />
				</Form.Item>

				<Form.Item label="是否启用" name="status" valuePropName="checked">
					<Switch onChange={ handleSwitchChange }/>
				</Form.Item>

			</Form>
		</Modal>
	);

} );

export default EmailSub;
